/*
 * Copyright (c) 2025, 廖树财, <study_2030@163.com>
 *
 * PEE2.0-YCYW-HY is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *         http://license.coscl.org.cn/MulanPSL2     
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

#pragma once
#include "openssl/md5.h"
#include "openssl/sha.h"
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdbool.h>
#include <stdint.h>
#include <time.h>
#include <sys/time.h>
#include <pthread.h>
#define BUFFER_SIZE 4096



typedef struct {
    char name[32];      // 网卡名称
    unsigned long long rx_total;  // 接收总量(上报平台)
    unsigned long long tx_total;  // 发送总量(上报平台)
    unsigned long long rx_prev;   // 查系统的实际接收总量
    unsigned long long tx_prev;   // 查系统的实际发送总量
    unsigned long long deltarx;     //与上次相比的接收增量
    unsigned long long deltatx;     //与上次相比的发送增量
    time_t second;      //时间年月
} NetInterface,*PNetInterface;

typedef struct {
    int minlen;
    int minclass;
    int lcredit;
    int ucredit;
    int dcredit;
    int ocredit;
    int is_open;    //0:disable, 1: enable
    int edit_prof;  //0: not modify, 1: modify
} password_policy_t;

typedef struct stru_CURRENT_ROMACONF
{
    char current_ServiceIp[16];
    int current_ServicePort;
    char current_Name[64];
    char current_DeviceSecret[64];
    char current_DevId[64];
    char current_NodeId[64];
    int current_EnableTLS;
} CURRENT_ROMACONF, * PCURRENT_ROMACONF;



//证书
typedef struct {
    char* country;
    char* surname;
    char* uid;
    char* commonName;
} SubjectInfo;

typedef struct {
    int port;
    int time;
    int status;//0 不改变 1 改变 2删除
} POLICY_PORT_PARAM;

typedef enum {
    POLICY_MQTT = 1,   // MQTT策略
    POLICY_SSH = 2,     // SSH策略
    POLICY_PORT = 3   // 端口策略
} PolicySecurityType;

typedef struct stru_POLICY_SECURITY_PARAM
{
	//video
	char forwardDev[50];   // 设备名
	char ipType[10];	 // 可选 不带ip-type参数时，默认ipv4
	char videoPlatformIp[20];   // 可选		默认使用固定摄像头ip
	char forwardStatus[20];
	char videoPlatformMasklen[10];
	char videoGateway[20];

	// port
	POLICY_PORT_PARAM portList[100];
    PolicySecurityType type; // port/mqtt/ssh
	int ssh; // ssh开启对应的延迟分钟
    int mqtt; // mqtt对应的延迟分钟
} POLICY_SECURITY_PARAM;

typedef struct st_IOTA_NETWORKLIST_PARAM_V2
{
    char operation[8];          //enum { ADD,DELETE,UPDATE}
    char chainDirection[8];     //enum { INPUT, FORWARD, OUTPUT }
    char permissionStatus[8];   //enum { DROP、ACCEPT }
    char protocol[8];           //enum { tcp、udp、icmp、sctp、all }
    char srcIp[64];             //源ip
    char srcPort[64];                //源端口
    char dstIp[64];             //目标ip
    char dstPort[64];                //目标端口
    char policyId[64];         //策略id
    char state[64];            //额外状态
    int prio;                   //优先级（1最优先，2往后）
    int ruleOrigin;             //来源字段 0：系统内置； 1：设备控制台手动设置； 2：平台下发新增； 3：平台端口封禁）
    int priority;               //预留，1：插队头；2：插队尾
    
    int already_matched;        //已被匹配过标识，非与平台交互字段
    char cmd[128];              //非与平台交互字段
} IOTA_NETWORKLIST_PARAM_V2, * PIOTA_NETWORKLIST_PARAM_V2;

typedef struct {
    IOTA_NETWORKLIST_PARAM_V2* rules;  // 动态数组
    int count;                         // 当前规则数
    int capacity;                      // 数组容量
} RuleCollection;


typedef struct st_IOTA_NETWORKLIST_PARAM_V3
{
    char policyId[128];         //策略id
    int newPrio;                //新的优先级
} IOTA_NETWORKLIST_PARAM_V3, * PIOTA_NETWORKLIST_PARAM_V3;

typedef struct IOTA_VL_CFG_PUSH_LOG
{
    char mid[64];        
    int code;
    char date[32];
} IOTA_VL_CFG_PUSH_LOG, *PIOTA_VL_CFG_PUSH_LOG;

// 雪花算法结构 (64位)
// 0 | 41位时间戳 | 10位机器ID | 12位序列号
#define TIMESTAMP_BITS 41
#define WORKER_ID_BITS 10
#define SEQUENCE_BITS 12

// 最大取值计算
#define MAX_WORKER_ID ((1 << WORKER_ID_BITS) - 1)
#define MAX_SEQUENCE ((1 << SEQUENCE_BITS) - 1)

// 时间戳偏移量（2020-01-01 00:00:00 UTC）
#define EPOCH 1577836800000LL

typedef struct {
    uint64_t last_timestamp;  // 上次生成ID的时间戳
    uint64_t worker_id;       // 工作机器ID
    uint64_t sequence;        // 序列号
    pthread_mutex_t mutex;    // 互斥锁
} Snowflake;

typedef enum {
    SINGLE_SOURCE_SINGLE_DEST,  //单个或者连续范围源端口匹配单个或者连续范围目标端口
    MULTI_SOURCE_SINGLE_DEST,   //多源端口匹配单个或者连续范围目标端口
    SINGLE_SOURCE_MULTI_DEST,   //单个或者连续范围源端口匹配多目标端口
    MULTI_SOURCE_MULTI_DEST,     //多源端口匹配多目标端口(系统不支持)
}CommunicationMode;

typedef struct stru_IOTA_ROMA_CONF_V1
{
    int resultCode;
    char* message;
    long timeStamp;

    char* deviceId;
    char* deviceAuthSecret;
    char* deviceAuthUser;
    char* mqttsIp;
    char* mqttsPort;
    char* mqttIp;
    char* mqttPort;
    int tls;
} IOTA_ROMA_CONF_V1;

void timeSleep(int ms);

int checkAndCreateDirectory(const char* path);

void calculate_md5(const char* file_path, char* md5_hash);

long calculate_file_size(const char* file_path);

unsigned int getstimeval();

//void GF_GetGUID(unsigned char* buf);
void GF_GetGUID(char* uuid);

int sql_dict(const char* key, char* value, const char parentid);

char** search_directory(const char* directory, const char* keyword, int* num_matches);

char* search_directory_firstone(const char* directory, const char* keyword);

char* get_absolute_path(const char* relative_path);

int dict_callback(void* data, int argc, char** argv, char** azColName);

int dec_passwd(char* encPasswd, char* decPasswd);

void get_os_name(char* osName);

void free_s(void* ptr);

int get_file_json(char* content, const char* filename);

int toGetMemUsed(int pid, char* res);

void remove_spaces(char* str);

int toGetCpuUsed(int pid, char* res);

int setstatus(int status);

void tosetroute();

void togettime_ym(char* date_ym);

int popen_get_json(char **json_string,const char *cmd);

void generate_random_string(char *str, size_t length);

void convert_to_ascii(const char* input, char* output, int mode);

int split_string(char* input, char tmp[4][6]);

uint64_t current_timestamp();

int snowflake_init(Snowflake* sf, uint64_t worker_id);

uint64_t snowflake_next_id(Snowflake* sf);

void snowflake_cleanup(Snowflake* sf);

double convert_string_to_double(const char* input);

int check_connectivity(const char* ip, int port, int timeout_sec);

int file_exists_v1(const char* filename);

time_t get_file_mod_time(const char* filename);

int set_iot_info_v1(int iotTlsCurrent);

int tar_czf_exec(const char* app_path, const char* file_id, const char* filename);

int chmod_exec(const char* app_path, const char* filename);

int run_sh_script_background(const char* app_path, const char* script_name, const char* arg);
